<script setup lang="ts">
import {
  ref,
  onMounted,
  reactive,
  getCurrentInstance,
  onUnmounted,
  nextTick,
} from 'vue'
// 组件
import { ElMessage } from 'element-plus'
// 接口
import type {
  IRoleData,
  IRoleQueryData,
  IRoleResponseData,
} from '@/api/system/role/type'
import type { IUserByRoleResponseData } from '@/api/divide/role/type'
import type { IUserData } from '@/api/system/user/type'
import type { ResponseData } from '@/types/common'
// api
import { reqRoleList } from '@/api/system/role/index'
import { reqRoleByUser, reqUserAssign } from '@/api/divide/role/index'

// 列表元素
let tableRef = ref()
// 用户id
let userId = ref<number>(0)
// 列表请求参数
let params = reactive<IRoleQueryData>({
  roleName: '',
  page: 1,
  limit: 10,
})
// 列表数据
let tableData = ref<IRoleData[]>([])
let oldTableData = ref<IRoleData[]>([])
// 总条数
let total = ref<number>(0)

// 更新视图
const updateTableView = () => {
  tableData.value = []
  nextTick(() => {
    tableData.value = oldTableData.value
  })
}
// 获取列表数据
const getList = async () => {
  const { code, message, data }: IRoleResponseData = await reqRoleList(params)
  const { total: listTotal, records } = data
  if (code === 200) {
    tableData.value = records || []
    oldTableData.value = records || []
    total.value = listTotal || 0
  } else {
    ElMessage({
      type: 'error',
      message,
    })
  }
}
// 根据用户id获取角色
const getRoleByUser = async (id: number) => {
  const { code, data }: IUserByRoleResponseData = await reqRoleByUser(id)
  if (code === 200) {
    setTableChecked(data.assignRoles)
  }
}
// 分页切换
const handlePageChange = (currentPage: number, pageSize: number) => {
  params.page = currentPage
  params.limit = pageSize
  getList()
}
// 搜索
const handleQuery = () => {
  getList()
}
// 重置筛选条件
const handleReset = () => {
  params.roleName = ''
  params.page = 1
  getList()
}
// 保存分配的角色
const handleSubmit = async () => {
  // 获取选中行
  const roleList = tableRef.value.getSelectionRows()
  if (!roleList.length) return
  const roleIdList = roleList.map((item: IRoleData) => {
    return item.id
  })
  const { code, message }: ResponseData = await reqUserAssign({
    userId: userId.value,
    roleIdList,
  })
  ElMessage({
    type: code === 200 ? 'success' : 'error',
    message,
  })
  getList()
}
// 设置列表页选中
const setTableChecked = (list: IRoleData[]) => {
  // 列表置空
  tableRef.value.clearSelection()
  if (!list.length) return
  // 勾选分配角色
  for (const item of list) {
    tableRef.value.toggleRowSelection(item, true)
  }
  updateTableView()
}

// 组件通信
const emitter =
  getCurrentInstance()?.appContext.config.globalProperties.$emitter

// 订阅
emitter.on('divide_user_row_click', (row: IUserData) => {
  userId.value = row.id
  // 根据用户id获取角色
  getRoleByUser(row.id)
})

onMounted(() => {
  getList()
})

onUnmounted(() => {
  // 移除订阅
  emitter.off('divide_user_row_click')
})
</script>
<template>
  <el-container>
    <!-- 筛选条件 -->
    <el-header>
      <el-form :model="params" inline>
        <el-form-item label="角色名">
          <el-input v-model="params.roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <!-- 表格 -->
    <el-main>
      <el-table ref="tableRef" :data="tableData" row-key="id" border>
        <el-table-column type="selection" align="center" reserve-selection />
        <el-table-column prop="roleName" label="角色名" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
      </el-table>
    </el-main>
    <!-- 分页 -->
    <el-footer>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-change="params.page"
        :page-size="params.limit"
        @change="handlePageChange"
      />
    </el-footer>
  </el-container>
</template>
